/*
 * @(#)UserDetailsServiceImpl.java
 * 2011-5-9 下午09:12:21
 *
 * Copyright (c) 2018-2028, HangZhou QiYun InfoTech Co.,Ltd. .
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.qyxx.platform.sysmng.accountmng.service;

import java.util.List;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.security.authentication.encoding.Md5PasswordEncoder;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.session.SessionAuthenticationException;
import org.springframework.transaction.annotation.Transactional;

import com.google.common.collect.Sets;
import com.qyxx.platform.sysmng.accountmng.entity.OnlineUser;
import com.qyxx.platform.sysmng.accountmng.entity.Role;
import com.qyxx.platform.sysmng.accountmng.entity.User;
import com.qyxx.platform.sysmng.utils.Constants;

/**
 *  实现SpringSecurity的UserDetailsService接口,实现获取用户Detail信息的回调函数
 *  
 *  @author gxj
 *  @version 1.0
 *  @since 1.6 2011-5-9 下午09:12:21
 */
@Transactional(readOnly = true)
public class UserDetailsServiceImpl implements UserDetailsService {

	private AccountManager accountManager;
	
	private OnlineUserManager onlineUserManager;

	/**
	 * 获取用户Details信息的回调函数.
	 */
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException {

		User user = accountManager.findUserByLoginName(username);
		/*if (user == null) {
			throw new UsernameNotFoundException("用户" + username + " 不存在");
		} else {
			if(Constants.DISABLED.equals(user.getStatus())) {
				throw new UsernameNotFoundException("用户" + username + "已经被禁用");
			}
		}
		if (!Constants.IS_SUPER_USERR.equals(user.getIsSuperAdmin())) {
			//非超级管理员时，判断用户名不能重复登录，针对在线用户列表中还存在该用户名
			List<OnlineUser> ouList = onlineUserManager.searchOnlineUser("loginUsername", username);
			if(null != ouList && ouList.size() >= 1) {
				throw new SessionAuthenticationException("登录名为" + username + "的用户已经登录中，如果您上次是非正常注销，请联系系统管理员");
			}
		}*/
		Set<GrantedAuthority> grantedAuths = obtainGrantedAuthorities(user);

		//-- mini-web示例中无以下属性, 暂时全部设为true. --//
		boolean enabled = true;
		boolean accountNonExpired = true;
		boolean credentialsNonExpired = true;
		boolean accountNonLocked = true;

		UserDetails userdetails = new org.springframework.security.core.userdetails.User(user.getLoginName(), user
				.getPassword(), enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, grantedAuths);

		return userdetails;
	}

	/**
	 * 获得用户所有角色集合.
	 */
	private Set<GrantedAuthority> obtainGrantedAuthorities(User user) {
		Set<GrantedAuthority> authSet = Sets.newHashSet();
		for (Role role : user.getRoleList()) {
			//for (Authority authority : role.getAuthorityList()) {
			authSet.add(new GrantedAuthorityImpl(role.getId() + Constants.UNDERLINE + role.getRoleName()));
			//}
		}
		return authSet;
	}

	@Autowired
	public void setAccountManager(AccountManager accountManager) {
		this.accountManager = accountManager;
	}
	
	
	/**
	 * @param onlineUserManager
	 */
	@Autowired
	public void setOnlineUserManager(OnlineUserManager onlineUserManager) {
		this.onlineUserManager = onlineUserManager;
	}

	public static void main(String[] args) {
	    Md5PasswordEncoder md5 = new Md5PasswordEncoder();  
	    System.out.println(md5.encodePassword("123456", "yb"));  
	}
}
